"""
用户账户相关的功能, 注册，登录，注销....
"""
import datetime
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Q
from apps.web.forms.account import RegisterModelForm, SendSmsForm, LoginForm, LoginSms, LoginPwdForm
from apps.web import models
from utils.verifycode import verify_code
from io import BytesIO
import uuid
# from django.core.exceptions import ValidationError


def register(request):
    """用户注册"""
    if request.method == 'GET':
        # 实列化对象
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})
    # 反之则为post请求
    # 验证数据
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()  # 在用户表中新建一条数据
        # 拿到价格策略的对象
        PriceProcily_obj  = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy= PriceProcily_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送验证码"""
    # 实例化对象
    form = SendSmsForm(data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    """短信验证码登录"""
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'web/login.html', {'form': form})
    # post请求
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 登录成功
        user_obj = models.UserInfo.objects.filter(email=form.cleaned_data.get('email')).first()
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """登录时发送验证码"""
    form = LoginSms(data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_pwd(request):
    """用户名密码登录"""
    if request.method == 'GET':
        # 实例化对象
        form = LoginPwdForm(request)
        return render(request, 'web/login_pwd.html', {'form': form})
    form = LoginPwdForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get('username')
        password = form.cleaned_data.get('password')
        user_obj = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_obj:
            # 登录成功
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('/index/')
        form.add_error('username', '用户名或密码错误')

    return render(request, 'web/login_pwd.html', {'form': form})


def img_code(request):
    """生成图片验证码"""
    img, code = verify_code()
    # 把code存入session中
    request.session['img_code'] = code
    # 给session设置超时时间
    request.session.set_expiry(60)  # 60秒
    # 把图片写到内存中
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())
